Today you will
Give the shop a memory: a database that keeps every product and sale after the program closes.
- Explain why a database beats a dictionary for a shop that runs every day.
- Describe a table, a row and a column, and see them in DB Browser.
- Import the
shop_dbhelper module and call its functions. - Ask the database your own questions with
SELECT ... WHERE. - Use what the database gives back with your Module 5 lists, dictionaries and loops.
Deep dive A: why do we need a database?
In Module 5 the price list was a dictionary. Run this, then run it again:
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
products["Bread Pudding"] = 6.00 # add a new product
print(products){'Beef Patty': 5.0, 'Coconut Tart': 4.0, 'Bread Pudding': 6.0}It prints the same thing every time. Bread Pudding isn't "still there" from the last run: the program adds it again, because when a program ends, its variables, lists and dictionaries are wiped. They only live in the computer's memory while the program is running.
A real shop needs to remember what it sold yesterday. A database saves the data in a file, so it's still there after the program closes, after you shut down Thonny, even after the computer restarts.
Deep dive B: tables, rows and columns
A database holds tables. A table looks like a spreadsheet tab. Our shop has two: products and sales. Here's the products table:
| id | name | price | stock |
|---|---|---|---|
| 1 | Beef Patty | 5.0 | 40 |
| 2 | Cheese Patty | 5.0 | 30 |
| 3 | Coconut Tart | 4.0 | 25 |
| 4 | Sorrel Drink | 3.5 | 20 |
- A row is one record: one product.
- A column is one kind of information: every product's price.
idis a number the database gives each row, so every product has its own label even if two had the same name.
This should feel familiar. One row is just like a Module 5 dictionary, and the whole table is like a list of dictionaries:
row = {"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40}
print(row["name"], "costs", row["price"])
table = [
{"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40},
{"id": 2, "name": "Cheese Patty", "price": 5.0, "stock": 30},
]
print(len(table), "rows")Beef Patty costs 5.0
2 rowsrow = {"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40}
print(row["name"], "costs", row["price"])
table = [
{"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40},
{"id": 2, "name": "Cheese Patty", "price": 5.0, "stock": 30},
{"id": 3, "name": "Bottled Water", "price": 4.50, "stock": 30}
]
print(len(table), "rows")
print(table[0]["name"], "price $",table[0]["price"], "amount in stock =", table[0]["stock"])
#this prints the item that we targeted
for item in table:
print(item["name"], "price $", item ["price"], "amount in stock =", item["stock"])
#This loops through the dictionary and prints each itemBeef Patty costs 5.0
3 rows
Beef Patty price $ 5.0 amount in stock = 40
Beef Patty price $ 5.0 amount in stock = 40
Cheese Patty price $ 5.0 amount in stock = 30
Bottled Water price $ 4.5 amount in stock = 30
>>> Deep dive C: meet shop_db - our helper module
Talking to a database takes some extra code: connect to the file, run the command, save, close. To keep today about the ideas, that code lives in a ready-made file, shop_db.py. You import it, the same way you've imported Streamlit, and call its functions.
| Function | What it does |
|---|---|
shop_db.setup() | Creates shop.db with the starter products. Safe to run every time. |
shop_db.get_products() | Every product, as a list of dictionaries |
shop_db.find_product(name) | One product as a dictionary, or None |
shop_db.add_product(name, price, stock) | Adds a product, gives back a message |
shop_db.record_sale(name, qty) | Saves a sale and takes the stock down, gives back a message |
shop_db.query(sql) | Ask your own SQL question (Deep dive E) |
shop_db.reset() | Empty the shop and start again |
import shop_db
shop_db.setup()
products = shop_db.get_products()
print(len(products), "products")
print(products[0])
for p in products:
print(f"{p['name']:<14} EC${p['price']:5.2f} stock: {p['stock']}")4 products
{'id': 1, 'name': 'Beef Patty', 'price': 5.0, 'stock': 40}
Beef Patty EC$ 5.00 stock: 40
Cheese Patty EC$ 5.00 stock: 30
Coconut Tart EC$ 4.00 stock: 25
Sorrel Drink EC$ 3.50 stock: 20Everything from Module 5 works on what comes back: len(), [0] for the first item, p['name'] to look up a key, and a for loop to go through them all.
Deep dive D: look inside with DB Browser
shop.db is a real file. After running the code above it appears in the same folder. Open it to see the tables:- Open DB Browser for SQLite.
- Open Database, then choose
shop.dbin your course folder. - Click the Browse Data tab.
- Pick
productsfrom the Table list. There are your rows and columns. - Run a Python program that changes the shop, then press F5 in DB Browser to refresh.
Deep dive E: your first SQL - SELECT ... WHERE
shop_db.query(), which gives back the matching rows as a list of dictionaries.import shop_db
cheap = shop_db.query("SELECT name, price FROM products WHERE price < 5")
for p in cheap:
print(p["name"], p["price"])Coconut Tart 4.0
Sorrel Drink 3.5| Part | Means | Like... |
|---|---|---|
SELECT name, price | Which columns you want | Picking which keys to print |
FROM products | Which table | Which list |
WHERE price < 5 | Which rows: only the ones that match | An if inside the loop (Module 3) |
Text values go in single quotes inside the SQL, so they don't clash with the double quotes around the whole command:
import shop_db
tart = shop_db.query("SELECT name, price, stock FROM products WHERE name = 'Coconut Tart'")
print(tart)[{'name': 'Coconut Tart', 'price': 4.0, 'stock': 25}]Deep dive F: add a product - data that lasts
shop_db.add_product() saves a new product in the database. Run this once:import shop_db
print(shop_db.add_product("Bread Pudding", 6.00, 12))
print(shop_db.find_product("Bread Pudding"))Added Bread Pudding.
{'id': 5, 'name': 'Bread Pudding', 'price': 6.0, 'stock': 12}Now close the program and run the exact same thing a second time:
import shop_db
print(shop_db.add_product("Bread Pudding", 6.00, 12))
print(shop_db.find_product("Bread Pudding"))Bread Pudding is already in the shop.
{'id': 5, 'name': 'Bread Pudding', 'price': 6.0, 'stock': 12}Bread Pudding survived. The program closed, and the database still had it, which is exactly what the dictionary in Deep dive A couldn't do. And the shop won't add a second Bread Pudding: every product name must be unique, just like dictionary keys in Module 5.
Deep dive G: the helper does the heavy lifting
Selling something takes two changes: add a row to sales, and take the stock down in products. shop_db.record_sale() does both, checks you have enough first, and gives back a message.
import shop_db
print(shop_db.record_sale("Beef Patty", 3))
print(shop_db.record_sale("Coconut Tart", 30))
print(shop_db.record_sale("Pizza", 1))
print(shop_db.record_sale("Coconut Tart", 2))
print(shop_db.find_product("Coconut Tart"))Sold 3 x Beef Patty = EC$15.00. 37 left.
Only 25 Coconut Tart left.
Sorry, we don't sell Pizza.
Sold 2 x Coconut Tart = EC$8.00. 23 left.
{'id': 3, 'name': 'Coconut Tart', 'price': 4.0, 'stock': 23}The last line proves it: Coconut Tart's stock in the database went from 25 down to 23.
Deep dive H: back to Module 5
The database gives back lists and dictionaries, so everything you learned in Module 5 still works. Here the price list comes out of the database into a dictionary, and the Module 5 order total runs on it unchanged:
import shop_db
prices = {}
for p in shop_db.get_products():
prices[p["name"]] = p["price"]
print(prices)
order = ["Beef Patty", "Sorrel Drink", "Beef Patty"]
total = 0
for item in order:
total += prices[item]
print(f"Order total: EC${total:.2f}"){'Beef Patty': 5.0, 'Cheese Patty': 5.0, 'Coconut Tart': 4.0, 'Sorrel Drink': 3.5}
Order total: EC$13.501. Set up the shop
Put shop_db.py in your course folder first. Run this, then open shop.db in DB Browser.
# Module 6 - set up the shop database
# shop_db.py must be in the same folder as this file.
import shop_db
shop_db.setup()
print("Database ready: shop.db")
for p in shop_db.get_products():
print(f" {p['name']:<14} EC${p['price']:5.2f} stock: {p['stock']}")Database ready: shop.db
Beef Patty EC$ 5.00 stock: 40
Cheese Patty EC$ 5.00 stock: 30
Coconut Tart EC$ 4.00 stock: 25
Sorrel Drink EC$ 3.50 stock: 202. A till that remembers
The Module 4 till loop, but every sale is saved in the database. Run it, sell a few things, stop it, and run it again: the stock has gone down.
# Module 6 - a till that remembers every sale
import shop_db
shop_db.setup()
print("MENU")
for p in shop_db.get_products():
print(f" {p['name']:<14} EC${p['price']:5.2f} ({p['stock']} left)")
while True:
name = input("Product (or 'done'): ")
if name == "done":
break
qty = int(input("How many? "))
print(" ", shop_db.record_sale(name, qty))MENU
Beef Patty EC$ 5.00 (40 left)
Cheese Patty EC$ 5.00 (30 left)
Coconut Tart EC$ 4.00 (25 left)
Sorrel Drink EC$ 3.50 (20 left)
Product (or 'done'): Beef Patty
How many? 3
Sold 3 x Beef Patty = EC$15.00. 37 left.
Product (or 'done'): Pizza
How many? 1
Sorry, we don't sell Pizza.
Product (or 'done'): Coconut Tart
How many? 40
Only 25 Coconut Tart left.
Product (or 'done'): Coconut Tart
How many? 2
Sold 2 x Coconut Tart = EC$8.00. 23 left.
Product (or 'done'): done# Module 6 - a till that remembers every sale
import shop_db
shop_db.setup()
print("MENU")
for p in shop_db.get_products():
# Fixed the quote nesting inside the f-string by using single quotes for 'id'
print(f" {p['id']}. {p['name']:<12} EC${p['price']:5.2f} ({p['stock']} left)")
while True:
user_input = input("Product ID (or 'done'): ")
if user_input.lower() == "done":
break
# Convert the entered ID to an integer
product_id = int(user_input)
qty = int(input("How many? "))
# Find the product name that matches the ID entered
found_name = None
for p in shop_db.get_products():
if p["id"] == product_id:
found_name = p["name"]
break
if found_name:
print(" ", shop_db.record_sale(found_name, qty))
else:
print("⚠️ Invalid ID, please try again.")RUN IT AND SEE3. Extra (fast finishers): reports
Questions a shop owner asks, answered from the database. The low-stock query is a SELECT you could write yourself. The sales report comes ready-made from the helper.
# Module 6 - answer the shop owner's questions
import shop_db
print("Low stock (under 25):")
low = shop_db.query("SELECT name, stock FROM products WHERE stock < 25")
for p in low:
print(f" {p['name']}: {p['stock']} left")
print("Sales by product:")
for row in shop_db.sales_report():
print(f" {row['name']:<14} {row['qty']:>3} sold EC${row['money']:6.2f}")Low stock (under 25):
Coconut Tart: 23 left
Sorrel Drink: 20 left
Sales by product:
Beef Patty 3 sold EC$ 15.00
Coconut Tart 2 sold EC$ 8.00Bug hunt
This program crashes. Read the last line of the error, fix the bug, run it again.
# BUG HUNT - this program crashes.
# It should list every product under EC$5.
# 1. Run it. 2. Read the LAST line of the error. 3. Fix the bug.
import shop_db
shop_db.setup()
cheap = shop_db.query("SELECT name, prise FROM products WHERE price < 5")
for p in cheap:
print(p["name"], p["price"])Hints (open only if stuck)
- The error names the problem word. Find it in the code.
- Open the products table in DB Browser. What are the columns really called?
Words to know
| Word | Meaning |
|---|---|
| Database | Data saved in a file, so it lasts after the program closes |
| Table | Like a spreadsheet tab: rows and columns |
| Row / column | One record (one product) / one kind of information (price) |
| SQL | The language for asking a database questions |
SELECT ... FROM ... WHERE | Read these columns, from this table, only the rows that match |
import | Bring in another file's functions, like import shop_db |
shop.db | The database file itself, next to your programs |
Practice
Homework 6 (5%): my_shop.py
Put your own shop in the database. It must:
Submit your .py file, a screenshot of it running and your DB Browser screenshot, before the next module.
| Mark | Means |
|---|---|
| 5 | Runs and has everything |
| 3 | Runs with parts missing, or has errors |
| 1 | Started |
| 0 | Not submitted |
Quiz 6
Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).
ADDITIONAL - STREAMLIT APP - SNEAK PEEK 6
The shop database in a web page. Sell something with the button and it's saved in shop.db for good. The stock table, low-stock warnings and sales chart all read straight from the database.
# stock_app.py - Module 6 sneak peek: the shop database in the browser
# Run it with: streamlit run stock_app.py
# shop_db.py must be in the same folder.
import streamlit as st
import shop_db # Module 6: our own helper module
shop_db.setup()
st.title("Mama J's Stock Room")
names = []
for p in shop_db.get_products(): # Module 4 loop over a Module 5 list
names.append(p["name"])
choice = st.selectbox("Sell a product", names)
qty = st.number_input("How many?", min_value=1, value=1, step=1)
if st.button("Record sale"): # Module 3: if
st.info(shop_db.record_sale(choice, qty)) # saved to shop.db for good
st.subheader("Stock")
st.dataframe(shop_db.get_products()) # read again, so it shows the new stock
low = shop_db.query("SELECT name, stock FROM products WHERE stock < 10") # your own SQL
for p in low:
st.warning(f"Low stock: {p['name']} ({p['stock']} left)")
st.subheader("Sales so far")
report = shop_db.sales_report()
if report:
st.bar_chart(report, x="name", y="money")
else:
st.write("No sales yet - sell something above.")See the browser. Pick Coconut Tart, set How many? to 2, press Record sale:
Sold 2 x Coconut Tart = EC$8.00. 23 left.
The Stock table updates, and a bar chart of sales appears under "Sales so far".
Close the browser and run it again tomorrow - the sale is still there.Your mission today
Put it all together: solve a maze by following the walls, record your times, and race in Battle Mode.
Follow the walls to the exit
Uses the forward and turn commands from Module 5. Test in Python Mode before class and adjust the wait times and the wall distance (20) if the robot turns too far or stops too early.
# Module 6 - Robot missions: find the exit by following the walls
def forward(ms):
robot.set_motors(50, 50)
robot.wait(ms)
robot.stop()
def turn(direction):
if direction == "left":
robot.set_motors(-50, 50)
else:
robot.set_motors(50, -50)
robot.wait(400)
robot.stop()
for step in range(200):
if robot.get_sensor(0) > 20:
forward(150)
elif robot.get_sensor(1) > robot.get_sensor(2):
turn("left")
else:
turn("right")
print("Mission over")Your race log
Type your own maze times into the list. Keep this list: you'll use it in Module 7.
# Module 6 - Keep a log of your maze times (a list) and find your best
times = [42.5, 38.1, 35.9] # type your own times here, in seconds
best = min(times)
print("Runs:", len(times))
print("Best time:", best, "seconds")
print("Average:", round(sum(times) / len(times), 1), "seconds")Robot words
| Code | What it means |
|---|---|
| Algorithm | A plan of steps to solve a problem |
| Wall following | Keep turning towards space and moving forward to find an exit |
min(times) | The smallest number: your best time |
sum(times) / len(times) | The average |
| Battle Mode | Race other robots in real time |
Challenges
Try one at a time. Change the code, run it, and watch.
Challenge puzzle
Your times are [41.2, 39.8, 44.0]. What is your best time?
times = [41.2, 39.8, 44.0]
print(min(times))Show the answer
39.8Build puzzle
Fill in the blank to print the average time.
times = [40, 50, 60]
average = ______
print(average)Show the answer
sum(times) / len(times) # 50.0Quiz 6
Pass with 3 out of 5. Then take it for points in the quiz section of robotics.a3tech.uk.